﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExcelDna.Integration;
using Excel = Microsoft.Office.Interop.Excel;
using CrystalWind.Example.ExcelDna.CustomerExtentions;
using ExcelDna.Registration;
using System.Runtime.InteropServices;
 
namespace CrystalWind.Example.ExcelDna
{
    public class ExampleUdf
    {

        /// <summary>
        /// 必须使用ExcelFunction才能注册为自定义函数
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        [ExcelFunction]
        static public int Test1(int x)
        {
            return x;
        }

        /// <summary>
        /// 可以使用pia库操作excel,使用xlcall,设置IsMacroType = true
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        [ExcelFunction(IsMacroType = true)]
        static public string Test2()
        {
            ////获取当前调用者
            Excel.Range rng = DnaExtentions.GetCaller();
            return rng.Parent.Name;
        }


        /// <summary>
        /// 参数接受单元格引用,使用ExcelArgument(AllowReference =true),类型为object
        /// </summary>
        /// <param name="range"></param>
        /// <returns></returns>
        [ExcelFunction(IsMacroType =true)]
        static public string Test3([ExcelArgument(AllowReference =true)] object range)
        {
            var rng = range as ExcelReference;
            return rng.ToPiaRange().Parent.Name;
        }

        /// <summary>
        /// 设置为明确注册,所以必须在插件加载事件中用代码加载.
        /// nuget添加Excel-DNA Registration,自定义类MyAddin,在autoopen事件中注册
        /// </summary>
        /// <returns></returns>
        [ExcelFunction(ExplicitRegistration =true)]
        static public string Test4()
        {
            return "test4";
        }

        [ExcelFunction(IsMacroType =true)]
        static public string Test5()
        {
            Excel.Range rng = DnaExtentions.GetCaller().Offset[1,0];
            var funs = ExcelRegistration.GetExcelFunctions().Select(v => v.FunctionAttribute.Name).ToArray2D(MapArrayFunctionRegistration.Orientation.Vertical);
            rng.Resize[funs.GetLength(0),1].Value = funs;
            return "已注册方法";
        }

        [ExcelFunction(IsMacroType = true)]
        static public string Test6([ExcelArgument(AllowReference = true)] object sourceRange, [ExcelArgument(AllowReference = true)] object destRange)
        {
            if (sourceRange is ExcelReference rng)
            {
                object[,] array = rng.GetValue() as object[,];
                //DnaExtentions.GetCaller().Offset[1].Resize[array.GetLength(0), array.GetLength(1)].Value = array;

                //ExcelReference caller = XlCall.Excel(XlCall.xlfCaller) as ExcelReference;

                return "test";
            }

            return "复制数据";
        }
    }
}
